/*  
使用 npm i request 安装的（request是可以发送网络请求）
https://juejin.cn/post/6844903965608378381
 */
const request = require('request');
const http = require('http');

const server = http.createServer((req, res) => {
    res.setHeader('Content-Type', 'text/html;charset=utf-8');
    let requestUrl = req.url;
    if (requestUrl === '/proxy') {
        /* 盗取资源，非法 python 做爬虫，类似 */
        // 完成代理请求操作，向B域名发送请求
        let targetUrl = 'http://localhost:8081/';
        request({
            url: targetUrl,
            method: "Get",
        }, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                console.log(body)
                res.write(body);
                res.end();
            }
        });

    } else {
        // 如果不是才提供网页服务
        let html = `
        <!DOCTYPE html>
            <html lang="en">

            <head>
                <meta charset="UTF-8">
                <meta http-equiv="X-UA-Compatible" content="IE=edge">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>Document</title>
            </head>

            <body>
                <button id="btn">点击发送ajax请求-请求B域名</button>
                <hr/>
                <button id="btnProxy">点击发送ajax请求-请求A域名</button>
            </body>
            <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
            <script>
                // 点击 btn 按钮发送ajax请求
                let url = 'http://localhost:8081'; // B域名接口地址
                $('#btn').click(function () {
                    $.ajax({
                        url,
                        type: 'get',
                        dataType: 'json',
                        success: function (res) {
                            console.log(res);
                        }
                    })
                })
                
                // ajax 先请求自己的代理服务器
                $('#btnProxy').click(function () {
                    $.ajax({
                        url: 'http://localhost:8080/proxy',
                        type: 'get',
                        dataType: 'json',
                        success: function (res) {
                            console.log(res);
                        }
                    })
                })


            </script>
        </html>
    `; // 这个网页里面进行ajax请求

        res.write(html);
        res.end();
    }



});
const port = 8080;

server.listen(port, () => {
    console.log(`server is running at A域名 http://localhost:${port}`);
});